<?php
namespace app\index\controller;
use app\common\controller\Common;
use app\index\model\ActionLog;
use app\index\model\OrderNum;
use app\index\model\DeliveryChange;
use app\index\model\Customer;

use Exception;
use think\Log;

class Delivery extends Common{

    private $orderNum;
    private $deliveryChange;
    private $customer;
    private $actionLog;

    public function __construct()
    {
        parent::__construct();
        $this->orderNum = new OrderNum();
        $this->deliveryChange = new DeliveryChange();
        $this->customer = new Customer();
        $this->actionLog = new ActionLog();
    }

    public function selectCustomer(){
        $countryList = $this->customer->countryList();
        $this->assign([
            'list' => $countryList,
        ]);
        return $this->fetch('delivery/select_customer');
    }

    public function ajaxCustomerList(){
        $para['page'] = input('get.page', 1);
        $para['limit'] = input('get.limit', 10);
        $para['cCCCode'] = input('get.cCCCode');
        $para['cCusName'] = input('get.cCusName');
        $para['table'] = 'Customer';
        $result = $this->customer->getList($para);
        $data = $result['data'];
        $count = $result['count'];
        return $this->_success($data, $count);
    }
    
    /**
     * 批量变更单页面，销售=》计划 
     */
    public function index1(){
        return $this->fetch('delivery/index1');
    }

    /**
     * 批量变更单页面，计划=》销售 
     */
    public function index2(){
        return $this->fetch('delivery/index2');
    }

    /**
     * 交期变更列表
     */
    public function ajaxList(){
        $page = $this->_request('get.page', 1);
        $limit = $this->_request('get.limit', 10);
        $orderNo = $this->_request('get.key.order_no');
        $cCusName = $this->_request('get.key.customer_name');
        $type = $this->_request('get.type');
        $zhangTao = $this->_request('zhangtao', '账套类别');
        $UID = $_SESSION['LOGIN_UID'];
        if (empty($orderNo) && empty($cCusName)) {
            $result = [];
            $count = 0;
        } else {
            $result = $this->orderNum->getDeliveryList($page, $limit, $orderNo, $cCusName, $UID, $type);
            $result = $result->toArray();
            if (!empty($result)) {
                foreach($result as &$item) {
                    $item['num'] = $this->_convertGbk2Utf8($item['num']);
                    $item['desc'] = $this->_convertGbk2Utf8($item['desc']);
                    $item['orderNo'] = $item['num'].$item['desc'];
                    if ($item['orderType'] == 'YW') {
                        $item['ddLeiXing'] = '外销';
                    } elseif($item['orderType'] == 'NX') {
                        $item['ddLeiXing'] = '内销';
                    } else {
                        $item['ddLeiXing'] = '';
                    }
                    $ztInfo = $this->orderNum->findZhangTao($zhangTao, $item['zhangtao']);
                    if (!empty($ztInfo)) {
                        $item['zhangtao'] = $this->_convertGbk2Utf8($ztInfo['name']);
                    } else {
                        $item['zhangtao'] = '';
                    }
                    $orderChange = $this->deliveryChange->checkOrderChange($item['orderId'], $type);
                    $item['isChanging'] = !empty($orderChange) ? 1 : 0 ;
                    $item['record'] = $this->actionLog->getList(JQ_DD_BG, $item['orderId']);
                    if (!empty($item['record'])) {
                        foreach($item['record'] as &$val){
                            $val['uname'] = $this->_convertGbk2Utf8($val['uname']);
                        }
                    }
                    $item['currency'] = $this->_convertGbk2Utf8($item['currency']);
                    $item['cCusName'] = $this->_convertGbk2Utf8($item['cCusName']);
                    $item['cCusPPersonText'] = $this->_convertGbk2Utf8($item['cCusPPersonText']);
                    $item['deliveryDate'] = '';
                }
            }
            $count = $this->orderNum->count($orderNo, $cCusName, $UID, $type);
        }
        return $this->_success($result, $count);
    }

    /*
     * 销售=》计划  
     */
    public function addData1()
    {
        if (request()->isGet()) {
            return $this->fetch('delivery/add1');
        } elseif (request()->isPost()) {
            try{
                $paras = request()->put();//会自动将JSON报头的数据转为数组
                Log::record("ADD_DATA1: PARAS:". json_encode($paras));  
                foreach($paras as &$item){
                    $item['ddLeiXing'] = iconv('UTF-8', 'GBK', $item['ddLeiXing']);
                }
                $uname = $_SESSION["LOGIN_USER_NAME"];
                $uid = $_SESSION['LOGIN_UID'];
                $type = $this->_request('get.type', "计划员接收");


                $name = $this->_request('get.type', "待办订单接收和变更单接收");

//                dump($type);
//                dump($name);exit;

                $ret = $this->deliveryChange->saveData1($paras, $uname, $type, $uid,$name);
                return $this->_success($ret);      
            }catch(Exception $e){
                return $this->_error($e->getMessage());
            }
        } else {
            return $this->_error('不支持其他的请求方式');
        }
    }

    /*
     * 计划=》销售  
     */
    public function addData2()
    {
        if (request()->isGet()) {
            return $this->fetch('delivery/add2');
        } elseif (request()->isPost()) {
            try{
                $paras = request()->put();//会自动将JSON报头的数据转为数组
                Log::record("ADD_DATA2: PARAS:". json_encode($paras));  
                $uname = $_SESSION["LOGIN_USER_NAME"];
                $uid = $_SESSION['LOGIN_UID'];
                $this->deliveryChange->saveData2($paras, $uname, $uid);
                return $this->_success();      
            }catch(Exception $e){
                return $this->_error($e->getMessage());
            }
        } else {
            return $this->_error('不支持其他的请求方式');
        }
    }


    /**
     * 销售=》计划  变更单列表
     */
    public function changeList1(){
        return $this->fetch('delivery/change_index1');
    }

    /**
     * 获取变更单数据
     */
    public function ajaxChangeList(){
        $type = $this->_request('get.type', 1);
        $page = $this->_request('get.page', 1);
        $limit = $this->_request('get.limit', 10);
        $orderNo = $this->_request('get.key.order_no');
        $cCusName = $this->_request('get.key.customer_name');
        $status = $this->_request('get.key.status');
        $username = $this->_request('get.key.username');
        $zhangTao = $this->_request('zhangtao', '账套类别');
        $uid = $_SESSION["LOGIN_UID"];
        $privilege = $this->_request('get.key.privilege');
        $result = $this->deliveryChange->getList($page, $limit, $orderNo, $cCusName, $username, $type, $uid, $privilege,$status);
        $result = $result->toArray();
        if (!empty($result)) {
            foreach($result as &$item) {
                $item['username'] = $this->_convertGbk2Utf8($item['username']);
                $item['ctime'] = date('Y-m-d H:i:s', $item['ctime']);
                $item['num'] = $this->_convertGbk2Utf8($item['num']);
                $item['desc'] = $this->_convertGbk2Utf8($item['desc']);
                $item['orderNo'] = $item['num'].$item['desc'];
                if ($item['orderType'] == 'YW') {
                    $item['ddLeiXing'] = '外销';
                } elseif($item['orderType'] == 'NX') {
                    $item['ddLeiXing'] = '内销';
                } else {
                    $item['ddLeiXing'] = '';
                }
                $ztInfo = $this->orderNum->findZhangTao($zhangTao, $item['zhangtao']);
                if (!empty($ztInfo)) {
                    $item['zhangtao'] = $this->_convertGbk2Utf8($ztInfo['name']);
                } else {
                    $item['zhangtao'] = '';
                }
                $item['currency'] = $this->_convertGbk2Utf8($item['currency']);
                $item['cCusName'] = $this->_convertGbk2Utf8($item['cCusName']);
                $item['cCusPPersonText'] = $this->_convertGbk2Utf8($item['cCusPPersonText']);
            }
        }
        $count = $this->deliveryChange->count($orderNo, $cCusName, $username, $type, $uid, $privilege,$status);
        return $this->_success($result, $count);
    }

    /**
     * 计划=》销售  变更单列表
     */
    public function changeList2(){
        return $this->fetch('delivery/change_index2');
    }

    /**
     * 我的审核列表页面
     */
    public function verifyList(){
        $uid = $_SESSION["LOGIN_UID"];
        $this->deliveryChange->doReceiveTime($uid);
        return $this->fetch('delivery/verify_list');
    }

    /**
     * 我的审核列表数据
     */
    public function ajaxVerifyList(){
        $page = $this->_request('get.page', 1);
        $limit = $this->_request('get.limit', 10);
        $status = $this->_request('get.key.status');
        if($status === ""){
            $status = 1;
        }
        $orderNo = $this->_request('get.key.order_no');
        $cCusName = $this->_request('get.key.customer_name'); 
        $username = $this->_request('get.key.username'); 
        $zhangTao = $this->_request('zhangtao', '账套类别');   
        $uid = $_SESSION["LOGIN_UID"];
        $result = $this->deliveryChange->myVerifyList($page, $limit, $orderNo, $cCusName, $username, $status, $uid);
        $result = $result->toArray();
        if (!empty($result)) {
            foreach($result as &$item) {
                $item['username'] = $this->_convertGbk2Utf8($item['username']);
                $item['ctime'] = date('Y-m-d H:i:s', $item['ctime']);
                $item['num'] = $this->_convertGbk2Utf8($item['num']);
                $item['desc'] = $this->_convertGbk2Utf8($item['desc']);
                $item['orderNo'] = $item['num'].$item['desc'];
                if ($item['orderType'] == 'YW') {
                    $item['ddLeiXing'] = '外销';
                } elseif($item['orderType'] == 'NX') {
                    $item['ddLeiXing'] = '内销';
                } else {
                    $item['ddLeiXing'] = '';
                }
                $ztInfo = $this->orderNum->findZhangTao($zhangTao, $item['zhangtao']);
                if (!empty($ztInfo)) {
                    $item['zhangtao'] = $this->_convertGbk2Utf8($ztInfo['name']);
                } else {
                    $item['zhangtao'] = '';
                }
                $categories = $this->_convertGbk2Utf8($this->orderNum->getProductsFromOrder($item['orderId']));
                $item['categories'] = $categories;
                $customerInfo = $this->customer->getCustomer($item['cCusCode']);
                if (!empty($customerInfo)) {
                    $item['country'] = $customerInfo[0]['cCCName'];
                    $item['customer'] = $customerInfo[0]['cCusAbbName'];
                } else {
                    $item['country'] = '';
                    $item['customer'] = '';
                }
                //显示原来确认交期和新确认交期一样
                if ($item['date2'] == $item['delivery_date']) {
                    //读取变更前的确认交期
                    $log = $this->actionLog->findData($item['orderId'], JQ_DD_BG, 'date2');
                    if (!empty($log)) {
                        $item['date2'] = $log['from_data'];
                    }
                }
                if ($item['oldIsShow'] == $item['isShow']) {
                    //读取变更前的确认交期
                    $log = $this->actionLog->findData($item['orderId'], JQ_DD_BG, 'is_show');
                    if (!empty($log)) {
                        $item['oldIsShow'] = $log['from_data'];
                    }
                }
                $item['currency'] = $this->_convertGbk2Utf8($item['currency']);
                $item['cCusName'] = $this->_convertGbk2Utf8($item['cCusName']);
                $item['cCusPPersonText'] = $this->_convertGbk2Utf8($item['cCusPPersonText']);
            }
        }
        $count = $this->deliveryChange->myCount($orderNo, $cCusName, $username, $status, $uid);
        return $this->_success($result, $count);
    }

    /**
     * 审核订单1
     */
    public function doVerify(){
        try{
            $idStr = $this->_request('post.id');
            $status = $this->_request('post.status');
            if (strpos($idStr, ',')) {
                $ids = explode(',', $idStr);
            } else {
                $ids = [$idStr];
            }
            $uname = $_SESSION["LOGIN_USER_NAME"];
            $uid = $_SESSION["LOGIN_UID"];
            Log::record("DO_VERIFY: ID:". $idStr . " STATUS:". $status. " UNAME:". $uname. " UID:". $uid);  
            $this->deliveryChange->doVerify($ids, $status, $uid, $uname);
            return $this->_success();      
        }catch(Exception $e){
            return $this->_error($e->getMessage());
        }
    }

    /**
     * 审核节点
     */
    public function nodeList(){
        $id = $this->_request('get.id');
        $changeVerifier = $this->_request('get.change', 0);
        $list = $this->deliveryChange->nodeList($id);
        $list = $list->toArray();
        if (!empty($list)) {
            $mapStatus = ['未审核','审核中', '通过','不通过'];
            foreach($list as &$item) {
                $item['uid'] = $this->_convertGbk2Utf8(GetUserNameByUid($item['uid']));
                $log = $this->actionLog->findData($item['id'], JQ_SHY_BG, 'uid');
                if (!empty($log)) {
                    $item['log_show'] =1;
                } else {
                    $item['log_show'] = 0;
                }
                $item['status2'] = $item['status'];
                switch($item['status']){
                    case 0:
                        $item['status'] = '<strong style="color:#1E9FFF">'.$mapStatus[$item['status']].'</strong>';
                        break;
                    case 1:
                        $item['status'] = '<strong style="color:#f1c232">'.$mapStatus[$item['status']].'</strong>';
                        break;
                    case 2:
                        $item['status'] = '<strong style="color:#009688">'.$mapStatus[$item['status']].'</strong>'; 
                        break;
                    case 3:
                        $item['status'] = '<strong style="color:red">'.$mapStatus[$item['status']].'</strong>';
                        break;
                    default: break;
                }
            }
        }
        // 或者批量赋值
        $this->assign([
            'list' => $list,
            'changeVerifier' => $changeVerifier
        ]);
        return $this->fetch('delivery/node_list');
    }

    /**
     * Log记录列表
     */
    public function logList(){
        $ticketNo = $this->_request('get.ticket_no');
        $actionType = $this->_request('get.action_type');
        $type = $this->_request('get.type');
        $filterArray = [];
        $result = $this->actionLog->getList($actionType, $ticketNo);
        $mapStatus = ['关闭','开启'];
        $mapStatus2 = ['未审核','审核中', '通过','不通过'];
        if (!empty($result)) {
            $mapLog = config('web.map_log');
            foreach ($result as &$item) {
                if (array_key_exists($item['action_type'], $mapLog)) {
                    $mapData = $mapLog[$item['action_type']];
                    if (array_key_exists($item['action_name'], $mapData)) {
                        $item['action_name'] = $mapData[$item['action_name']];
                    }
                }
                if ($actionType == JQ_DD_BG) {
                    //根据订单id查找所有的变更人
                    $users = $this->deliveryChange->getAllVerifyName($ticketNo, $type);
                    $users = $users->toArray();
                    if (!empty($users)) {
                        $users = _array_column($users, 'uid');
                        $userName = GetUserNameByUid(implode(',', $users));
                    } else {
                        $userName = '';
                    }
                }
                if ($actionType == JQ_DD_BG) {
                    $item['uname'] = $this->_convertGbk2Utf8($userName);
                } else {
                    $item['uname'] = $this->_convertGbk2Utf8($item['uname']);
                }
                $item['ctime'] = date('Y-m-d H:i:s', $item['ctime']);
                $item['mtime'] = date('Y-m-d H:i:s', $item['mtime']);
                if ($item['action_name'] == '订单状态') {
                    $item['from_data'] = $mapStatus[$item['from_data']];
                    $item['to_data'] = $mapStatus[$item['to_data']];
                    array_push($filterArray, $item);
                } elseif ($item['action_name'] == '状态'){
                    $item['from_data'] = $mapStatus2[$item['from_data']];
                    $item['to_data'] = $mapStatus2[$item['to_data']];
                } elseif ($item['action_name'] == '修改时间') {
                    if (!empty($item['from_data'])) {
                        $item['from_data'] = date('Y-m-d H:i:s', $item['from_data']);
                    }
                    $item['to_data'] = date('Y-m-d H:i:s', $item['to_data']);
                } elseif ($item['action_name'] == '办理人') {
                    $item['from_data'] = $this->_convertGbk2Utf8(GetUserNameByUid($item['from_data']));
                    $item['to_data'] = $this->_convertGbk2Utf8(GetUserNameByUid($item['to_data']));
                    array_push($filterArray, $item);
                } elseif ($item['action_name'] == '确认交期') {
                    array_push($filterArray, $item);
                }
                
            }
        }
        $uname = $time = '无';
        // 变更人
        if (!empty($result)) {
            $uname = $result[0]['uname'];
            $time = $result[0]['mtime'];
        }
        // 或者批量赋值
        $this->assign([
            'uname'  => $uname,
            'time' => $time,
            'list' => $filterArray,
        ]);
        return $this->fetch('log/index');
    }

    /**
     * 
     */
    public function changeList3(){
        $type = $this->_request('get.type', 0);
        $orderNo = $this->_request('get.orderNo');
        $this->assign([
            'bgStatus'  => $type,
            'orderNo' => $orderNo,
        ]);
        return $this->fetch('delivery/modify_verifier');
    }

    /**
     * 修改审核员
     */
    public function doModifyVerifer(){
        try{
            $id = $this->_request('post.id');
            $uname1 = $this->_request('post.uname');
            $uname2 = $_SESSION["LOGIN_USER_NAME"];
            $this->deliveryChange->modifyVerifer($id, $uname1, $uname2);
            return $this->_success();      
        }catch(Exception $e){
            return $this->_error($e->getMessage());
        }
    }
    
    
    
}
?>